package ua.org.extjsbuilder.parser.runtime.data;

import java.io.IOException;
import java.io.Writer;
import java.util.Collections;
import java.util.List;

import ua.org.extjsbuilder.parser.IInstruction;
import ua.org.extjsbuilder.parser.IScope;
import ua.org.extjsbuilder.parser.JSObject;

public class JSFunction implements IInstruction, JSObject {
	private String name;
	private List<IInstruction> arguments;
	private List<IInstruction> body;

	public JSFunction(String name, List<IInstruction> arguments,
			List<IInstruction> body) {
		this.name = name;
		this.arguments = arguments;
		this.body = body;
	}

	public JSObject execute(IScope scope, JSObject[] args) {
		//if(scope==null)scope=this;
		//TODO: set args
		return JSConstants.UNDEFINED;
	}

	public void compile(Writer out, boolean optimize) throws IOException {
		if(optimize){
			renameArguments();
		}
		out.write("function(");
		if(name!=null&&name.length()>0){
			out.write(' ');
			out.write(name);
		}
		out.write('(');
		for(int i=0;i<arguments.size();i++){
			if(i>0)out.write(',');
			//out.write(getAlly(arguments.get(i)));
		}
		out.write(')');
		out.write('{');
		
		for(IInstruction instr : body){
			instr.compile(out, optimize);
		}
		
		out.write('}');
		out.write(';');
	}

	private void renameArguments() {
		//for(String name : arguments){
			//generateAlly(name);
		//}
	}

	public String getName() {
		return name;
	}

	public List<IInstruction> getBody() {
		return Collections.unmodifiableList(body);
	}
}
